package com.example.novelsys.controller;

import com.example.novelsys.entity.Categories;
import com.example.novelsys.entity.Users;
import com.example.novelsys.service.CategoriesService;
import com.example.novelsys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    CategoriesService categoriesService;
    @Autowired
    UserService userService;

    //跳转登录-注册页面
    @RequestMapping("/toLogonRegister")
    public String toLogonRegister(HttpServletRequest req) {
        List indexInfo = new ArrayList();
        //1、获取小说类别
        List<Categories> categoriesList = categoriesService.queryAll();
        indexInfo.add(categoriesList);

        req.setAttribute("indexInfo", indexInfo);

        return "login-register";

    }

    //用户注册
    @PostMapping("/register")
    @ResponseBody
    public Integer register(Users user){
        //注册会员
        int i = userService.addUser(user);

        //响应结果
        return  i;
    }


    //用户登录
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String username,String pwd ,HttpServletRequest req) {

        //查询用户
        List<Users> userList = userService.queryByName(username);

        //存放响应结果
        Map result=new HashMap<String, Object>();

        //登录结果判断
        if(userList ==null || userList.size()==0) {//不存在该用户账号
            result.put("code", 0);

        }else {//遍历用户们，密码是否匹配
            for(Users user: userList) {
                if(pwd !=null &&  pwd.equals(user.getPwd())) {//登录成功

                    //绑定session对象
                    HttpSession session = req.getSession();
                    session.setAttribute("user", user);

                    result.put("code", 1);
                    result.put("username",username);

                    break;

                }else {//登录失败
                    result.put("code", 2);
                }

            }
        }

        return result;

    }

//退出登录
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req)  {
        //退出，移除session
        HttpSession session = req.getSession();
        session.removeAttribute("user");

        return "redirect:/";
    }


}
